package main

import (
	"encoding/base64"
	"fmt"
	"io"
	"log"
	"os"
	"path"
	"strings"
	"time"

	"github.com/tonny-zhang/cotton"
)

var dir = "./timg"

func clearImg() {
	if files, e := os.ReadDir(dir); e == nil {
		timeLine := time.Now().Add(-time.Minute * 10)
		for i := range files {
			file := files[i]
			if info, einfo := file.Info(); einfo == nil && info.ModTime().Before(timeLine) {
				filepath := path.Join(dir, file.Name())
				if e := os.RemoveAll(filepath); e == nil {
					log.Default().Println("删除文件", filepath)
				}
			}
		}
	}
}
func main() {
	r := cotton.Default()

	go func() {
		clearImg()
		ticker := time.NewTicker(time.Minute * 5)
		for range ticker.C {
			clearImg()
		}
	}()
	r.Post("/upload", func(ctx *cotton.Context) {
		base64Image := ctx.GetPostForm("image")

		index := strings.IndexByte(base64Image, ',')
		if index < 0 {
			ctx.JSON(500, cotton.M{
				"msg": "格式错误",
			})
			return
		}
		b64data := base64Image[index+1:]

		des := base64.NewDecoder(base64.StdEncoding, strings.NewReader(b64data))

		os.MkdirAll(dir, os.ModePerm)
		filename := fmt.Sprintf("%d.png", time.Now().Nanosecond())
		f, e := os.Create(path.Join(dir, filename))
		if e == nil {
			defer f.Close()

			_, e = io.Copy(f, des)
		}

		if e == nil {
			ctx.JSON(200, cotton.M{
				"img": dir + "/" + filename,
			})
		} else {
			ctx.JSON(500, cotton.M{
				"msg": e.Error(),
			})
		}
	})

	r.Run(":8010")
}
